package net.simpleframework.workflow.schema;

import java.io.InputStream;
import java.io.Reader;

import net.simpleframework.core.AbstractXmlDocument;
import net.simpleframework.workflow.schema.AbstractProcessStartupType.Manual;

import org.dom4j.Element;

/**
 * 这是一个开源的软件，请在LGPLv3下合法使用、修改或重新发布。
 * 
 * @author 陈侃(cknet@126.com, 13910090885)
 *         http://code.google.com/p/simpleframework/
 *         http://www.simpleframework.net
 */
public class ProcessDocument extends AbstractXmlDocument {
	public ProcessDocument(final InputStream inputStream) {
		super(inputStream);
	}

	public ProcessDocument(final Reader reader) {
		super(reader);
	}

	public ProcessDocument() {
		super(ProcessDocument.class.getClassLoader().getResourceAsStream(
				"net/simpleframework/workflow/schema/null-pdl.xml"));
	}

	private ProcessNode processNode;

	@Override
	public String toString() {
		getProcessNode().syncElement();
		return super.toString();
	}

	public ProcessNode getProcessNode() {
		if (processNode == null) {
			processNode = new ProcessNode((Element) getRoot().elementIterator().next());
		}
		return processNode;
	}

	public static void main(final String[] args) {
		testDocument();
	}

	static void testDocument() {
		final ProcessDocument doc = new ProcessDocument();
		// final ProcessDocument doc = new
		// ProcessDocument(ProcessDocument.class.getClassLoader()
		// .getResourceAsStream("net/simpleframework/workflow/schema/pdl.xml"));
		// System.out.println(doc.getProcessNode().getId());
		final ProcessNode processNode = doc.getProcessNode();
		processNode.setAuthor("cknet");
		processNode.setText("My first process!");
		processNode.setDescription("My first process!");
		final AbstractProcessStartupType.Manual manual = (Manual) processNode.getStartupType();
		((AbstractProcessParticipantType.User) manual.getParticipantType()).setParticipant("cknet");

		final StartNode start = processNode.startNode("start-node");
		final EndNode end = processNode.endNode("end-node");
		final UserNode node1 = processNode.addNode("user-node-1", UserNode.class);
		((AbstractUserNodeParticipantType.User) node1.getParticipantType()).setParticipant("cknet");
		final UserNode node11 = processNode.addNode("user-node-11", UserNode.class);
		final UserNode node12 = processNode.addNode("user-node-12", UserNode.class);
		processNode.addTransition(start, node1);
		processNode.addTransition(node1, node11);
		processNode.addTransition(node1, node12);
		processNode.addTransition(node11, end);
		processNode.addTransition(node12, end);
		System.out.println(doc.toString());
	}
}
